package cn.supermaster.management.web.service.system.impl;

import cn.supermaster.management.common.response.WebResponse;
import cn.supermaster.management.common.utils.ServletUtils;
import cn.supermaster.management.common.utils.TextUtils;
import cn.supermaster.management.web.service.system.ISLoginService;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * All rights Reserved, Designed By www.super-bytecode.com
 *
 * @ProjectName: supermaster-management
 * @Package: cn.supermaster.management.web.service.system.impl
 * @ClassName: SLoginServiceImpl
 * @Description: []
 * <p> </p>
 * @Author: [Lance Ting]
 * @Date: 2021/2/19 22:55
 * @Version: V1.0
 * @Copyright: 2021 www.super-bytecode.com Inc. All rights reserved.
 * TODO: 注意,本文件Lance Ting所作,如果转载或使用请标明具体出处!
 **/
@Service
public class SLoginServiceImpl implements ISLoginService {

    /**
     * @Description: []
     * <p></P>
     * @Title: skipLoginHtml
     * @Author: Lance Ting
     * @Date: 2021-02-19
     * @Param: request
     * @Param: response
     * @Return: java.lang.String
     */
    @Override
    public String skipLoginHtml(HttpServletRequest request, HttpServletResponse response) {
        // 如果是Ajax请求，返回Json字符串。
        if (ServletUtils.isAjaxRequest(request)) {
            Map<String, String> res = new HashMap<>();
            res.put("code", "1");
            res.put("msg", "未登录或登录超时。请重新登录");
            return ServletUtils.renderString(response, JSON.toJSONString(res));
        }
        return "login";
    }

    /**
     * @Description: []
     * <p></P>
     * @Title: skipUnauthHtml
     * @Author: Lance Ting
     * @Date: 2021-02-19
     * @Return: java.lang.String
     */
    @Override
    public String skipUnauthHtml() {
        return "error/unauth";
    }

    /**
     * @Description: []
     * <p></P>
     * @Title: doLogin
     * @Author: Lance Ting
     * @Date: 2021-02-19
     * @Param: username
     * @Param: password
     * @Param: rememberme
     * @Return: cn.supermaster.management.common.response.WebResult
     */
    @Override
    public WebResponse doLogin(String username, String password, Boolean rememberme) {
        UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberme);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            return WebResponse.success();
        } catch (AuthenticationException e) {
            String msg = "用户或密码错误";
            if (TextUtils.isNotEmpty(e.getMessage())) {
                msg = e.getMessage();
            }
            return WebResponse.failure(msg);
        }
    }
}